<?php

namespace App\Http\Controllers\Home;

use App\Http\Model\Article;
use App\Http\Model\Category;
use App\Http\Model\Comment;
use App\Http\Model\Images;
use App\Http\Model\Star;
use App\Http\Model\User;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Session;

class IndexController extends Controller
{
    /**
     * 前台首页
     * @return $this
     */
    public function index(){
        $bannerArticle=Article::select('article.title','article.id','user.username','article.banner')
            ->where('article.banner','!=','')->where('article.status',1)
            ->join('user','user.id','=','article.user_id','left')
            ->orderBy('article.created_at','desc')->limit(5)->get()->all();
        $mainContent=$this->indexList(1);
        return view('home.index',compact('bannerArticle','mainContent'))->with(['title'=>'首页','authorinfo'=>'']);
    }

    /**
     * 首页的加载更多
     * @param $page
     * @return array
     */
    public function indexList($page){
        $articleContent=DB::table('article')->select('article.title','article.cover','article.created_at',
            'article.banner','article.id','article_content.content','user.username','user.avatar','category.category')
            ->join('article_content','article_content.article_id','=','article.id','left')
            ->join('user','user.id','=','article.user_id','left')
            ->join('category','category.id','=','article.category_id','left')
            ->where(['article.status'=>1])->orderBy('article.created_at','desc')->offset(($page-1)*12)->limit(12)->get();
        foreach($articleContent as $k=> $item){
            if(isset($item->content)){
                $articleContent[$k]->content=mb_substr(strip_tags(trim(strip_tags($item->content))),0,150,'utf-8');
            }
        }
        $imageContent=DB::table('images')->select('user.username','user.avatar','images.created_at',
            'images.title','images.images','images.id','category.category')
            ->join('user','user.id','=','images.user_id','left')
            ->join('category','category.id','=','images.category_id','left')
            ->where(['images.status'=>1])->orderBy('images.created_at','desc')->offset(($page-1)*12)->limit(12)->get();
        $mainContent=array_merge($articleContent,$imageContent);
        shuffle($mainContent);
        return $mainContent;
    }

    /**
     * 文章详情页
     * @param $id 文章id
     * @return $this
     */
    public function articleDetail($id){
        Article::where('id',$id)->increment('views',1);
        $article=Article::select('article.title','article.category_id','article.user_id','article.id',
            'article.created_at','article.views','article_content.content','star.uid')
            ->join('article_content','article_content.article_id','=','article.id','left')
            ->join('star','star.id','=','article.id','left')
            ->where(['article.id'=>$id])->get()->all()[0];
        $articles=Article::select('article.title','article.category_id','article.id','article.created_at',
            'article.cover','article_content.content','user.username','user.avatar','category.category')
            ->join('article_content','article_content.article_id','=','article.id','left')
            ->join('user','user.id','=','article.user_id','left')
            ->join('category','category.id','=','article.category_id','left')
            ->where('article.category_id',$article['category_id'])->limit(17)
            ->orderByRaw('RAND()')->get()->all();
        /*取评论*/
        $comments=$this->getComment($id);
        $starCommentIds=$this->getCommentIds();
        /*获取关注作者所有的人*/
        $guanzhu=Star::select('uid')->where(['type'=>3,'id'=>$article['user_id']])->get()->all();
        $guan=[];
        foreach($guanzhu as $g){
            $guan[]=$g['uid'];
        }
        $authorInfo=User::select('username','avatar','id')->find($article['user_id']);
        return view('home.articledetail',compact('starCommentIds','guan','article','comments','articles'))
            ->with(['authorinfo'=>$authorInfo,'title'=>$article['title']]);
    }

    /**
     * 图册详情
     * @param $id 图册id
     * @return $this
     */
    public function imageDetail($id){
        Images::where('id',$id)->increment('views',1);
        $image=Images::select('images.title','images.category_id','images.user_id','star.uid','images.images',
            'images.created_at','images.describe','images.views','images.id')
            ->join('star','star.id','=','images.id','left')->where('images.id',$id)->get()->all()[0];
        /*取评论*/
        $comments=$this->getComment($id);
        /*猜你喜欢*/
        $images=Images::select('user.username','user.avatar','images.created_at','images.title','images.images',
            'images.id','category.category')
            ->join('user','user.id','=','images.user_id','left')
            ->join('category','category.id','=','images.category_id','left')
            ->where('images.category_id',$image['category_id'])->limit(12)->orderByRaw('RAND()')->get()->all();
        $starCommentIds=$this->getCommentIds();
        /*获取关注作者所有的人*/
        $guanzhu=Star::select('uid')->where(['type'=>3,'id'=>$image['user_id']])->get()->all();
        $guan=[];
        foreach($guanzhu as $g){
            $guan[]=$g['uid'];
        }
        $authorInfo=User::select('username','avatar','id')->find($image['user_id']);
        return view('home.imagedetail',compact('starCommentIds','guan','image','comments','images'))
            ->with(['authorinfo'=>$authorInfo,'title'=>$image['title']]);
    }

    /**
     * 取用户(当前登录者)这篇文章所有点赞的id
     * @return array
     */
    private function getCommentIds(){
        $CommentIds=Star::select('id')->where(['uid'=>Session::get('user')['id'],'type'=>4])->get()->all();
        $starCommentIds=[];
        foreach($CommentIds as $starCommentId){
            $starCommentIds[]=$starCommentId->id;
        }
        return $starCommentIds;
    }

    /**
     * 获取这篇文章的评论
     * @param $id 文章id
     * @return mixed
     */
    private function getComment($id){
        $comments['like']=Comment::select('comment.id','comment.like','comment.cid','comment.uid',
            'comment.created_at','comment.comment','user.avatar','user.username')->
        join('user','user.id','=','comment.uid','left')->where(['cid'=>$id,'reply'=>-1])
            ->orderBy('like','desc')->limit(10)->get();
        $comments['new']=Comment::select('comment.id','comment.like','comment.cid','comment.uid',
            'comment.created_at','comment.comment','user.avatar','user.username')->
        join('user','user.id','=','comment.uid','left')->where(['cid'=>$id,'reply'=>-1])
            ->orderBy('id','desc')->limit(10)->get();
        $comments['old']=Comment::select('comment.id','comment.like','comment.cid','comment.uid',
            'comment.created_at','comment.comment','user.avatar','user.username')->
        join('user','user.id','=','comment.uid','left')->where(['cid'=>$id,'reply'=>-1])
            ->orderBy('id','asc')->limit(10)->get();
        foreach($comments as $key1=>$comment){
            foreach($comment as $key2=> $c){
                $comments[$key1][$key2]['replycount']=Comment::where('reply',$c['id'])->count();
            }
        }
        return $comments;
    }

    /**
     * 获取文章
     * @param $page 页数
     * @param int $category_id 分类id
     * @return mixed
     */
    public function getAList($page,$category_id=-1){
        return $this->getArticles($page,$category_id);
    }

    /**
     * 文章列表页
     * @param $page 页数默认1
     * @param int $category_id 分类id
     * @return $this
     */
    public function articleList($page,$category_id=-1){
        $category=$category_id==-1?'全部文章':Category::select('category')->find($category_id)->category;
        $articles=$this->getArticles($page,$category_id);
        return view('home.articlelist',compact('articles','category_id'))
            ->with(['title'=>$category,'authorinfo'=>'']);
    }

    /**
     * 获取文章列表
     * @param $page 页数
     * @param $category_id 分类id
     * @return mixed
     */
    private function getArticles($page,$category_id){
        if($category_id==-1){
            /*全部分类*/
            $categorys=Category::select('id')->where(['type'=>1,'status'=>1])->get()->all();
            $cate_id=[];
            foreach($categorys as $c){
                $cate_id[]=$c['id'];
            }
            $articles=DB::table('article')->whereIn('category_id',$cate_id)
                ->select('article.title','article.created_at','article.cover','category.category',
                    'article.banner','article.id','article_content.content','user.avatar','user.username')
                ->join('article_content','article_content.article_id','=','article.id','left')
                ->join('user','user.id','=','article.user_id','left')
                ->join('category','category.id','=','article.category_id','left')
                ->where(['article.status'=>1])->orderBy('article.created_at','desc')
                ->offset(($page-1)*24)->limit(24)->get();
        }else{
            $articles=DB::table('article')->where('category_id',$category_id)
                ->select('article.title','article.created_at','article.cover','article.banner','category.category',
                    'article.id','article_content.content','user.avatar','user.username')
                ->join('article_content','article_content.article_id','=','article.id','left')
                ->join('user','user.id','=','article.user_id','left')
                ->join('category','category.id','=','article.category_id','left')
                ->where(['article.status'=>1])->orderBy('article.created_at','desc')
                ->offset(($page-1)*24)->limit(24)->get();
        }
        foreach($articles as $k=> $item){
            if(isset($item->content)){
                $articles[$k]->content=mb_substr(strip_tags(trim(strip_tags($item->content))),0,150,'utf-8');
            }
        }
        return $articles;
    }

    /**
     * 获取图册列表
     * @param $page
     * @param $category_id
     * @return mixed
     */
    private function getImages($page,$category_id){
        if($category_id==-1){
            /*全部分类*/
            $categorys=Category::select('id')->where(['type'=>2,'status'=>1])->get()->all();
            $cate_id=[];
            foreach($categorys as $c){
                $cate_id[]=$c['id'];
            }
            $images=DB::table('images')->select('user.username','user.avatar','images.created_at',
                'images.title','images.images','images.id','category.category')
                ->join('user','user.id','=','images.user_id','left')
                ->join('category','category.id','=','images.category_id','left')
                ->whereIn('images.category_id',$cate_id)->where(['images.status'=>1])
                ->orderBy('images.created_at','desc')->offset(($page-1)*20)->limit(20)->get();
        }else{
            $images=DB::table('images')->select('user.username','user.avatar','images.created_at',
                'images.title','images.images','images.id','category.category')
                ->join('user','user.id','=','images.user_id','left')
                ->join('category','category.id','=','images.category_id','left')
                ->where('images.category_id',$category_id)->where(['images.status'=>1])
                ->orderBy('images.created_at','desc')->offset(($page-1)*20)->limit(20)->get();
        }
        return $images;
    }

    /**
     * 获取更多文章
     * @param $page 页数
     * @param int $category_id 分类id
     * @return $this
     */
    public function imageList($page,$category_id=-1){
        $category=$category_id==-1?'全部图片':Category::select('category')->find($category_id)->category;
        $images=$this->getImages($page,$category_id);
        return view('home.imagelist',compact('images','category_id'))->with(['title'=>$category,'authorinfo'=>'']);
    }

    /**
     * 获取更多图册
     * @param $page 页数
     * @param int $category_id 分类id
     * @return mixed
     */
    public function getIList($page,$category_id=-1){
        return $this->getImages($page,$category_id);
    }

    /**
     * 保存评论
     * @return array
     */
    public function insertComment(){
        if($input=Input::except('_token')){
            if(!Session::get('user')){
                return ['status'=>0,'msg'=>'您未登录'];
            }else{
                $input['comment']=trim($input['comment']);
                if(empty($input['comment'])){
                    return ['status'=>0,'msg'=>'评论不能为空'];
                }
                $input['uid']=Session::get('user')['id'];
                if(isset($input['reply'])){
                    $input['read']=0;
                }
                return Comment::create($input)?['status'=>1,'msg'=>'评论成功']:['status'=>0,'msg'=>'评论失败'];
            }
        }
    }

    /**
     * 获取和此评论id相关的评论（评论详情）
     * @param $id 评论id
     * @return $this
     */
    public function commentDetail($id){
        $c1=Comment::select('comment.id','comment.like','comment.cid','comment.uid','comment.created_at',
            'comment.comment','user.avatar','user.username')
            ->join('user','user.id','=','comment.uid','left')->where('comment.id',$id)
            ->orderBy('id','desc')->get()[0];
        $c1['replycount']=Comment::where('reply',$c1['id'])->count();
        $comments=Comment::select('comment.id','comment.like','comment.cid','comment.uid',
            'comment.created_at','comment.comment','user.avatar','user.username')->
        join('user','user.id','=','comment.uid','left')->where('comment.reply',$id)->get()->all();
        foreach($comments as $key2=> $c){
            $comments[$key2]['replycount']=Comment::where('reply',$c['id'])->count();
        }
        $starCommentIds=$this->getCommentIds();
        $uidsc=Star::select('uid')->where(['id'=>$id,'type'=>4])->limit(5)->get()->all();
        $uids=[];
        foreach($uidsc as $uid){
            $uids[]=$uid['uid'];
        }
        $avatars=User::select('avatar')->whereIn('id',$uids)->get()->all();
        return view('home.commentdetail',compact('c1','avatars','starCommentIds','comments'))
            ->with(['title'=>'评论详情','authorinfo'=>'']);
    }

    /**
     * 文章图册的搜索
     * @return $this
     */
    public function search(){
        if($title=Input::get('title')){
            $article=$image=[];
            /*使用sphinx*/
            require(base_path().'/sphinx/sphinxapi.php');
            $sph=new \SphinxClient();
            $sph->setServer('127.0.0.1',9312);
            $pageSize=30;
            $sph->setLimits ((1-1)*$pageSize,$pageSize);
            $artsph=$sph->Query($title,'hh_article');
            $imgsph=$sph->Query($title,'hh_images');
            /*提取id*/
            if($artsph['total_found']>0){
                $artids=array_keys($artsph['matches']);
                $article=Article::whereIn('article.id',$artids)
                    ->select('article.title','article.created_at','article.cover','article.banner',
                        'article.id','article_content.content','user.avatar','user.username')
                    ->join('article_content','article_content.article_id','=','article.id','left')
                    ->join('user','user.id','=','article.user_id','left')
                    ->where(['article.status'=>1])->get()->all();
            }
            if($imgsph['total_found']>0){
                $imgids=array_keys($imgsph['matches']);
                $image=Images::select('user.username','user.avatar','images.title','images.images','images.id')
                    ->join('user','user.id','=','images.user_id','left')
                    ->whereIn('images.id',$imgids)->get()->all();
            }
            $mainContent=array_merge($article,$image);
            shuffle($mainContent);
            return view('home.search',compact('mainContent'))->with(['title'=>'搜索：'.$title,'authorinfo'=>'']);
        }
    }
}
